<template>
  <div class="upload-file">
    <el-upload
      multiple
      action=""
      :file-list="fileList"
      :limit="limit"
      :show-file-list="false"
      :headers="headers"
      :before-upload="handleBeforeUpload"
      :on-error="handleUploadError"
      :on-exceed="handleExceed"
      :on-success="handleUploadSuccess"
      class="upload-file-uploader"
      ref="fileUpload"
      :auto-upload="true"
      :http-request="onUpload"
    >
      <!-- 上传按钮 -->
      <el-button size="mini" type="primary">选取文件</el-button>
      <!-- 上传提示 -->
      <div class="el-upload__tip" slot="tip" v-if="showTip">
        请上传
        <template v-if="fileType"
          >格式为
          <b style="color: #f56c6c">{{ fileType.join("/") }}</b></template
        >
        的文件
      </div>
    </el-upload>

    <el-progress
      v-show="showProgress"
      :stroke-width="6"
      :percentage="progress"
    ></el-progress>

    <!-- 文件列表 -->
    <transition-group
      class="upload-file-list el-upload-list el-upload-list--text"
      name="el-fade-in-linear"
      tag="ul"
    >
      <li
        :key="file.url"
        class="el-upload-list__item ele-upload-list__item-content"
        v-for="(file, index) in fileList"
      >
        <el-link :href="`${file.url}`" :underline="false" target="_blank">
          <span class="el-icon-document"> {{ getFileName(file.name) }} </span>
        </el-link>
        <div class="ele-upload-list__item-content-action">
          <el-link :underline="false" @click="handleDelete(index)" type="danger"
            >删除</el-link
          >
        </div>
      </li>
    </transition-group>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { getOssConfig, deleteOssFile } from "@/api/menu";

const OSS = require("ali-oss");
let ossClient = null; // oss客户端实例

export default {
  name: "FileUpload",
  props: {
    // 值
    value: [String, Object, Array],
    // 数量限制
    limit: {
      type: Number,
      default: 5,
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 2048,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["xls", "xlsx", "doc", "docx", "txt", "rar", "zip", "pdf"],
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      number: 0,
      uploadList: [],
      baseUrl: process.env.VUE_APP_BASE_API,
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/common/uploadBigFile", // 上传文件服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      fileList: [],
      showProgress: false,
      progressPercent: 0, // 进度条百分比
      //同步进度条
      progress: 0,
      requestId: null,
      websocket: null,
      isWebSocketInitialized: false,
      files: [],
      checkpoints: {},
    };
  },
  watch: {
    value: {
      handler(val) {
        if (val) {
          let temp = 1;
          // 首先将值转为数组
          const list = Array.isArray(val) ? val : this.value.split(",");
          // 然后将数组转为对象数组
          this.fileList = list.map((item) => {
            if (typeof item === "string") {
              item = { name: item, url: item };
            }
            item.uid = item.uid || new Date().getTime() + temp++;
            return item;
          });
        } else {
          this.fileList = [];
          return [];
        }
      },
      deep: true,
      immediate: true,
    },
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
  },
  created() {},
  methods: {
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      // 校检文件类型
      if (this.fileType) {
        const fileName = file.name.split(".");
        const fileExt = fileName[fileName.length - 1];
        const isTypeOk = this.fileType.indexOf(fileExt) >= 0;
        if (!isTypeOk) {
          this.$modal.msgError(
            `文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`
          );
          return false;
        }
      }
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传文件大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      this.progress = 0;
      this.number++;
      this.files.push(file);
      return true;
    },
    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传失败
    handleUploadError(err) {
      this.$modal.msgError("上传文件失败，请重试");
      // this.$modal.closeLoading();
      this.showProgress = false;
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      console.log("上传成功回调");
      if (res.code === 200) {
        this.uploadList.push({ name: res.fileName, url: res.fileName });
        this.uploadedSuccessfully();
        this.showProgress = false; // 隐藏进度条
      } else {
        this.number--;
        // this.$modal.closeLoading();
        this.$modal.msgError(res.msg);
        this.$refs.fileUpload.handleRemove(file);
        this.showProgress = false;
        this.uploadedSuccessfully();
      }
    },
    // 删除文件
    handleDelete(index) {
      console.log(index);
      let deleteFile = this.fileList[index];
      this.fileList.splice(index, 1);
      this.files.splice(index, 1);
      this.uploadList.splice(index, 1);
      this.$emit("input", this.listToString(this.fileList));
      //删除文件同时，删除oss
      console.log(deleteFile);
      let fileName = deleteFile.name.replace(
        "https://bridgebj.oss-cn-beijing.aliyuncs.com/",
        ""
      );
      // console.log(",,,", fileName);
      deleteOssFile({ fileName });
    },
    // 上传结束处理
    uploadedSuccessfully() {
      console.log(this.number, "number得数量");
      console.log(this.uploadList.length, "length得长度");

      if (this.number > 0 && this.uploadList.length === this.number) {
        this.fileList = this.fileList.concat(this.uploadList);
        this.uploadList = [];
        this.number = 0;
        this.$emit("input", this.listToString(this.fileList));
        // this.$modal.closeLoading();
        this.showProgress = false;
        this.progress = 0;
      }
    },
    // 获取文件名称
    getFileName(name) {
      if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1);
      } else {
        return "";
      }
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let strs = "";
      separator = separator || ",";
      for (let i in list) {
        strs += list[i].url + separator;
      }
      return strs != "" ? strs.substr(0, strs.length - 1) : "";
    },
    //上传
    onUpload() {
      console.log("上传中");
      //获取临时sts凭证
      getOssConfig()
        .then((res) => {
          let { accessKeyId, accessKeySecret, securityToken, expiration } =
            res.data;
          ossClient = new OSS({
            accessKeyId: accessKeyId,
            accessKeySecret: accessKeySecret,
            stsToken: securityToken,
            bucket: "bridgebj", //todo
            secure: true,
            region: "oss-cn-beijing", //todo
            expiration: expiration,
          });
          if (ossClient) {
            console.log("开始上传");
            this.files.forEach((file) => {
              console.log(file);
              // 如果文件大学小于分片大小，使用普通上传，否则使用分片上传
              this.multipartUpload(file);
            });
          } else {
            console.log("ossClient null");
            this.showProgress = false;
            this.progress = 0;
          }
        })
        .catch((err) => {
          console.log(err);
          console.log("err null");
          this.showProgress = false;
          this.progress = 0;
        });
    },
    // 分片上传
    multipartUpload(file) {
      console.log("multipartUpload");
      console.log(file);
      this.showProgress = true;
      let fileName = file.name;

      // let dateFolder = this.timestamp();
      return ossClient
        .multipartUpload("file/" + Date.now() + "-" + fileName, file, {
          parallel: 5,
          partSize: 1024 * 1024 * 3,
          progress: this.onMultipartUploadProgress,
          timeout: 1800000, //设置超时时间
        })
        .then((result) => {
          console.log("上传成功");
          console.log(file.name);
          this.uploadList.push({
            name: result.name,
            url: "https://bridgebj.oss-cn-beijing.aliyuncs.com/" + result.name,
          });
          this.uploadedSuccessfully();
          console.log(result);
        })
        .catch((err) => {
          console.log("上传失败");
          console.log(`Multipart upload ${file.name} failed === `, err);
          this.showProgress = false;
          this.progress = 0;
        });
    },
    // 分片上传进度改变回调
    onMultipartUploadProgress(progress, checkpoint) {
      console.log(Math.round(progress * 100));
      let newprogress = Math.round(progress * 100);
      this.progress = newprogress > this.progress ? newprogress : this.progress;
    },
    timestamp() {
      var time = new Date();
      var y = time.getFullYear();
      var m = time.getMonth() + 1;
      var d = time.getDate();
      var h = time.getHours();
      var mm = time.getMinutes();
      var s = time.getSeconds();
      console.log(y);
      return (
        "" +
        y +
        "/" +
        this.add0(m) +
        "/" +
        this.add0(d) +
        "/" +
        this.add0(h) +
        "/" +
        this.add0(mm) +
        "/" +
        this.add0(s)
      );
    },
    add0(m) {
      return m < 10 ? "0" + m : m;
    },
  },
};
</script>

<style scoped lang="scss">
.upload-file-uploader {
  margin-bottom: 5px;
}

.upload-file-list .el-upload-list__item {
  border: 1px solid #e4e7ed;
  line-height: 2;
  margin-bottom: 10px;
  position: relative;
}

.upload-file-list .ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
}

.ele-upload-list__item-content-action .el-link {
  margin-right: 10px;
}
</style>
